<?php
namespace app\talbum\service;
use app\talbum\model\VideoModel as va;
use app\talbum\validata\TablumValidata as tv;
use app\base\service\BaseService;
use think\facade\Log;
use Env;

require_once Env::get('root_path').'/extend/aliyun/aliyunphpsdk/aliyunphpsdkcore/Config.php';   // 假定您的源码文件和aliyun-php-sdk处于同一目录
use aliyun\aliyunphpsdk\aliyunphpsdkvod\vod\Request\V20170321 as vod;
use aliyun\aliyunphpsdk\aliyunphpsdkcore\profile\DefaultProfile;
use aliyun\aliyunphpsdk\aliyunphpsdkcore\DefaultAcsClient;
use aliyun\aliyunphpsdk\aliyunphpsdkvod\vod\Request\V20170321\CreateUploadVideoRequest;
class VideoService extends BaseService 
{
	protected $video ='';
	protected $tv='';
	 public function __construct()
	 {
	 	parent::__construct();
	 	$this->video = new va;
	 	$this->tv = new tv;
	 }
     //初始化阿里云客户端
  public function init_vod_client($accessKeyId, $accessKeySecret) {
    $regionId = 'cn-shanghai';  // 点播服务所在的Region，国内请填cn-shanghai，不要填写别的区域
    $profile = DefaultProfile::getProfile($regionId, $accessKeyId, $accessKeySecret);
    return new DefaultAcsClient($profile);
  }
// $client为上面init_vod_client接口返回的客户端对象
// $videoId为视频ID
protected function get_play_info($client, $videoId) {
  $request = new vod\GetPlayInfoRequest();
  $request->setVideoId($videoId);
  $request->setAcceptFormat('JSON');
  return $client->getAcsResponse($request);
}
public function object_array($array) {  
    if(is_object($array)) {  
        $array = (array)$array;  
     } if(is_array($array)) {  
         foreach($array as $key=>$value) {  
             $array[$key] = object_array($value);  
             }  
     }  
     return $array;  
}
//  $playInfo = $this->get_play_info($client, '1ecdb760407644f5b54966422fccc0fe');
//调用视频凭证接口
protected function alivideo($video){
    // 注意捕获异常
try {
     $client = $this->init_vod_client('LTAIwFahh1g15C5m', '4zGS3Qa195rvg1OkYJCBCIp9ltpe2F');
  if(isset($video['videoid'])&&!empty($video['videoid'])){
      $playInfo = $this->refresh_upload_video($client, $video['videoid']);
      return $this->return_code(200,"成功",array($playInfo));
  }else{

  }
    $data['title']='test';
    $data['file']='57a884f9ebf9140f3d5946c6f748ad4d.mp4';
    $playInfo = $this->create_upload_video($client, $data);
    return $this->return_code(200,"成功",array($playInfo));
} catch (Exception $e) {
   print $e->getMessage();
}

}

//上传视频到阿里云获得视频凭证等等
protected function create_upload_video($client,$data) {
    $request = new CreateUploadVideoRequest();
    $request->setTitle((isset($data['title'])&&!empty($data['title']))?$data['title']:"视频标题");        // 视频标题(必填参数)
    $request->setFileName($data['file']); // 视频源文件名称，必须包含扩展名(必填参数)
    if((isset($data['desc'])&&!empty($data['desc']))){
        $request->setDescription($data['desc']);  // 视频源文件描述(可选)
    }
    if((isset($data['coverimage'])&&!empty($data['coverimage']))){
           $request->setCoverURL($data['coverimage']); // 自定义视频封面(可选)
    }
     if((isset($data['flag'])&&!empty($data['flag']))){
          $request->setTags($data['flag']); // 视频标签，多个用逗号分隔(可选)
    }
  
    $request->setAcceptFormat('JSON');
    return $client->getAcsResponse($request);
} 

//刷新获得视频到阿里云获得视频凭证等等
protected function refresh_upload_video($vodClient, $videoId) {
    $request = new vod\RefreshUploadVideoRequest();
    $request->setVideoId($videoId);
    return $vodClient->getAcsResponse($request);
}

	 //上传视频
	protected function insert_videos($data){
		if (!$this->tv->scene('add_video')->check($data)) {
            return $this->return_code(300,$this->tv->getError());
        }
         $perm = $this->permissions($data['Openid']);
        if($perm['code'] !=10000&&$perm['code']!=10001)   return $this->return_code(301,"对不起，权限不足");
        //通过Openid获得用户信息
        if(isset($data['Openid'])&&!empty($data['Openid'])){
        	$userinfo = $this->get_userinfo($data['Openid']);
        	
        }else{
        	$userinfo = $this->user;
        }
        $video['createtime'] =time();  
		$video['Isuse'] =0;
		$video['ordernum'] =0;
		$video['Hits'] =0;
		$video['Token'] =$userinfo['Token'];
		$video['Userid'] =$this->user["Userid"];
		$video['Openid'] =$this->user["Openid"];
		$video['videoname'] =$data["videoname"];
		$video['describe'] =$data["describe"];
		$video['permissions'] =$data["permissions"];
		$video['videoregion'] =$data["videoregion"];
	
		if(isset($data['cover'])&&!empty($data['cover'])&&!is_null($data['cover'])){
			$image=$this->upload_one_img($data['cover']);
			if($image['code']!=200)  return $this->return_code($image['code'],$image['msg']);
			$video['cover'] = $image['imagepath'];
		}
		if(isset($data['video'])&&!empty($data['video'])&&!is_null($data['video'])){
			$videos=$this->upload_one_video($data['video']);
			if($videos['code']!=200)  return $this->return_code($videos['code'],$videos['msg']);
			$video['video'] = $videos['imagepath'];
		}
		
        $id = $this->video->insert('video_album',$video);
        if($id){
        	 return $this->return_code(200,'视频上传成功');
        }
        return  $this->return_code();
	}

	//视频列表
	protected function video_list($data){
		if (!$this->tv->scene('comment_list')->check($data)) {
            return $this->return_code(300,$this->tv->getError());
        }
   		$perm = $this->permissions($data['Openid']);
      
        //通过Openid获得用户信息
        if(isset($data['Openid'])&&!empty($data['Openid'])){
        	$userinfo = $this->get_userinfo($data['Openid']);
        }else{
        	$userinfo = $this->user;
        }
        switch ($perm['code']) {
        	case '10000':
        		break;
   			case '10001'://家人
        		 $where['permissions']   = array('neq' => 3);
        		break;
		   	case '10002'://好友
				$where['permissions']   = array('neq' => 3);
			break;
        	default:
        		$where['permissions']   = 1;
        		break;
        }
      
		$where['Token']=$userinfo['Token'];
		return  $this->return_code(200,'成功',$this->video->loadAllData("video_album","*",$where,$data['page'],$data['limit'],$order="videoid desc"));
	}

	//查看评论
	  public function comment_list($data){
	  	if (!$this->tv->scene('comment_list')->check($data)) {
            return $this->return_code(300,$this->tv->getError());
        }
        $res = $this->video->comment_list($data,$data['page'],$data['limit']);
        return $res;
	  }

	  //添加评论
	  	protected function comments($data){
		if (!$this->tv->scene('video_comment')->check($data)) {
            return $this->return_code(300,$this->tv->getError());
        }
        $comment=[
        	'content'=>$data['content'],
        	'Openid' =>$this->user['Openid'],
        	'createtime'=>time(),
        	'Userid' => $this->user['Userid'],
        	'ordernum' =>0,
        	'Hits'=>0,
        	'number'=>0,
        	'videoid'=>$data['videoid'],
        	'Token'=>$this->user['Token'],
        	'Replayid'=>$data['Replayid']
        ];
         $id = $this->video->comment($comment);
         if($id){
        	 return $this->return_code(200,'评论成功');
        }
        return  $this->return_code();

	}

//获得点赞数 和
	public function get_count($data)
	{
		if (!$this->tv->scene('get_counts')->check($data)) {
            return $this->return_code(300,$this->tv->getError());
        }
        $res = $this->video->get_count($data);
        return $res;
	}


	  //点赞和取消
        protected function add_points($data){
        if (!$this->tv->scene('add_pointv')->check($data)) {
            return $this->return_code(300,$this->tv->getError());
        }
        $where['Openid'] = $this->user['Openid'];
        $where['videoid'] = $data['videoid'];

        $point = $this->video->findByAttributes('video_album_point',$where,'status');
     if(empty($point)){
        $point=[
            'Openid' =>$this->user['Openid'],
            'createtime'=>time(),
            'Userid' => $this->user['Userid'],
            'videoid' =>$data['videoid'],
            'status' =>1,
        ];
         $id = $this->video-> insert('video_album_point',$point);
         if($id){
             return $this->return_code(200,'点赞成功');
        }
     }else{
        if($point['status'] == 1){
            $up['status']=2; 
        }else{
            $up['status']=1; 
        }
         $up_p = $this->video->updateByWhere('video_album_point',$where,$up);
         if($up_p)   return $this->return_code(200,'成功');
     }
        
        
        return  $this->return_code();

    }


}